package com.compass.doctor.ui.patient

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityAddInquiryCaseHistoryBinding
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.doctor.ui.prescription.DiagnoseActivity
import com.compass.framework.constant.KEY_CASE_ID
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.KEY_ORDER_ID
import com.compass.framework.constant.KEY_PATIENT_ID
import com.compass.framework.constant.KEY_TITLE
import com.compass.framework.constant.REFRESH_MESSAGE
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.textChangeFlow
import com.compass.framework.ext.visible
import com.compass.framework.model.CreationInquiryCase

import com.compass.framework.model.Diagnosis
import com.compass.framework.model.InquiryCase
import com.compass.framework.utils.BigDecimalUtils
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.MoneyInputFilter
import com.compass.framework.utils.getDrawableResource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 * Description： 病历---添加问诊/编辑病历/病历详情病--需要同步his的
 * Date:2024/3/9 9:44
 */
class AddInquiryCaseHistory : BaseVBActivity<ActivityAddInquiryCaseHistoryBinding>() {


    companion object {
        fun start(
            context: Context,
            patientId: String?,
            diseaseDescription: String?,
            caseId: String?,
            consultationId: String?,
            comeType:Int?
        ) {
            val intent = Intent(context, AddInquiryCaseHistory::class.java)
            intent.putExtra(KEY_PATIENT_ID, patientId)
            intent.putExtra(KEY_TITLE, diseaseDescription)
            intent.putExtra(KEY_CASE_ID, caseId)
            intent.putExtra(KEY_ORDER_ID, consultationId)
            intent.putExtra(KEY_CONSULT_TYPE, comeType)
            context.startActivity(intent)
        }
    }

    private val patientViewModel: PatientViewModel by viewModels()
    private lateinit var inquiryCase: CreationInquiryCase
    private var patientId: String? = null//患者id
    private var caseId: String? = null//病历id
    private var consultationId: String? = null//问诊id

    private var comeType: Int? = null//从那个界面进来的 0 查看病历  1.添加病历  2 问诊待办结束
    private var diseaseDescription: String? = null //主诉
    private var temperature: String? = null
    private var breathing: String? = null
    private var heartRate: String? = null
    private var height: String? = null
    private var weight: String? = null
    private var bmi: String? = null
    private var sphygmus: String? = null//脉搏
    private var dbp: String? = null
    private var sbp: String? = null

    private var entrust:String?= null //嘱托
    private var physiqueInspect:String? = null //体格检查

    private var diagnosisId: String? = null //初步诊断code
    private var pastHistoryStatus: Int = 1 //既往史状态
    private var pastHistoryContent: String? = null  //既往史
    private var presentDiseaseStatus: Int = 1 //现病史状态
    private var presentDiseaseContent: String? = null //现病史
    private var allergyHistoryStatus: Int = 1 //过敏状态
    private var allergyHistoryContent: String? = null //过敏史

    private lateinit var diagnosis: Diagnosis//接收返回的诊断数据

    //诊断回调
    private val mActivityResultLauncher: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    diagnosis = intent.serializable("diagnosis")!!


                    mBinding.tvDiagnosis.text = diagnosis.name
                    diagnosisId = diagnosis.id
                }
            }
        }

    override fun initView(savedInstanceState: Bundle?) {
        patientId = intent.getStringExtra(KEY_PATIENT_ID)
        caseId = intent.getStringExtra(KEY_CASE_ID)
        consultationId = intent.getStringExtra(KEY_ORDER_ID)
        comeType = intent.getIntExtra(KEY_CONSULT_TYPE,0)
        diseaseDescription = intent.getStringExtra(KEY_TITLE)
        diseaseDescription?.let {
            mBinding.edtMainSuit.setText(diseaseDescription)
        }
        setInputRestrict()

    }

    //设置输入框限制
    private fun setInputRestrict() {
        //身高
//        val filterHi = MoneyInputFilter()
//        filterHi.setMaxValue(300.0)
//        filterHi.setDecimalLength(2)
//        mBinding.edtHeight.filters = arrayOf(filterHi)
//
//        //体重
//        val filterWe = MoneyInputFilter()
//        filterWe.setMaxValue(500.0)
//        filterWe.setDecimalLength(2)
//        mBinding.edtWeight.filters = arrayOf(filterWe)
//
//
//        //体温
//        val filter = MoneyInputFilter()
//        filter.setMaxValue(50.0)
//        filter.setDecimalLength(2)
//        mBinding.edtTemperature.filters = arrayOf(filter)

        //呼吸次数
//        val filterBreath = MoneyInputFilter()
//        filterBreath.setMaxValue(100.0)
//        filterBreath.setDecimalLength(0)
//        mBinding.edtBreathing.filters = arrayOf(filterBreath)

        //心率/脉搏
//        val filterHeart = MoneyInputFilter()
//        filterHeart.setMaxValue(300.0)
//        filterHeart.setDecimalLength(0)
//        mBinding.edtHeartRate.filters = arrayOf(filterHeart)
//        mBinding.edtPulse.filters = arrayOf(filterHeart)

        //舒张压
//        val filterDbp = MoneyInputFilter()
//        filterDbp.setMaxValue(300.0)
//        filterDbp.setDecimalLength(0)
//        mBinding.edtDbp.filters = arrayOf(filterDbp)

        //收缩压
//        val filterSbp = MoneyInputFilter()
//        filterSbp.setMaxValue(300.0)
//        filterSbp.setDecimalLength(0)
//        mBinding.edtSbp.filters = arrayOf(filterSbp)
    }

    override fun initData() {
        caseId?.let {
            patientViewModel.getPatientCaseHistoryDetailsHis(it)
        } ?: kotlin.run {
            isNeedListener(true)
        }


        patientViewModel.addSuccessLiveData.observe(this) {
            dismissLoading()
            it?.let {
                showToast("添加病历成功")
                finish()
            }

        }
        patientViewModel.inquiryCaseLiveData.observe(this) {
            it?.let { inquiryCase ->
                setCaseInfo(inquiryCase)
            }
        }
        patientViewModel.addSuccessForPhoneLiveData.observe(this){
            dismissLoading()
            it?.let {
                LiveDataBus.get().with(REFRESH_MESSAGE).postValue( REFRESH_MESSAGE)
                showToast("操作成功")
                finish()
            }
        }
    }

    private fun setCaseInfo(inquiryCase: InquiryCase) {
        if (inquiryCase.editingStatus == 1) {
            isNeedListener(true)
            mBinding.llButton.visible()
            mBinding.tvTitleBar.setMiddleText("编辑病历")
        } else {
            mBinding.tvTitleBar.setMiddleText("病历详情")
            isNeedListener(false)
            mBinding.llButton.gone()
        }
        consultationId=inquiryCase.consultationId
        diagnosisId=inquiryCase.diagnosisId
        mBinding.edtMainSuit.setText(inquiryCase.diseaseDescription)
        mBinding.edtPastHistory.setText(inquiryCase.pastHistoryContent)
        mBinding.edtPHI.setText(inquiryCase.presentDiseaseContent)
        mBinding.edtAllergicHistory.setText(inquiryCase.allergyHistoryContent)
        setPastHistory(inquiryCase.pastHistoryStatus)
        setPresentDisease(inquiryCase.presentDiseaseStatus)
        setAllergyHistory(inquiryCase.allergyHistoryStatus)

        mBinding.tvDiagnosis.text=inquiryCase.diagnosisText

        mBinding.edtEntrust.setText(inquiryCase.entrust)
        mBinding.edtPhysicalExam.setText(inquiryCase.physiqueInspect)
//        mBinding.edtHeight.setText(inquiryCase.height)
//        mBinding.edtWeight.setText(inquiryCase.weight)
//        mBinding.edtBmi.text = inquiryCase.bmi
//        mBinding.edtTemperature.setText(inquiryCase.temperature)
//        mBinding.edtPulse.setText(inquiryCase.sphygmus)
//        mBinding.edtBreathing.setText(inquiryCase.breathe)
//        mBinding.edtHeartRate.setText(inquiryCase.heartRate)
//        mBinding.edtDbp.setText(inquiryCase.dbp)
//        mBinding.edtSbp.setText(inquiryCase.sbp)

    }

    /**
     * 既往史设置
     */
    private fun setPastHistory(status: Int) {
        pastHistoryStatus = status
        when (pastHistoryStatus) {
            1 -> {
                mBinding.edtPastHistory.visible()
                setDrawableLeft(mBinding.btnNotHavePastHistory, false)
                setDrawableLeft(mBinding.btnHavePastHistory, true)
            }

            0 -> {
                mBinding.edtPastHistory.gone()
                setDrawableLeft(mBinding.btnNotHavePastHistory, true)
                setDrawableLeft(mBinding.btnHavePastHistory, false)
            }
        }

    }

    /**
     * 现病史
     */
    private fun setPresentDisease(status: Int) {
        presentDiseaseStatus = status
        when (presentDiseaseStatus) {
            1 -> {
                mBinding.edtPHI.visible()
                setDrawableLeft(mBinding.btnHavePHI, true)
                setDrawableLeft(mBinding.btnNotHavePHI, false)
            }

            0 -> {
                mBinding.edtPHI.gone()
                setDrawableLeft(mBinding.btnHavePHI, false)
                setDrawableLeft(mBinding.btnNotHavePHI, true)
            }
        }

    }

    /**
     * 过敏史
     */
    private fun setAllergyHistory(status: Int) {
        allergyHistoryStatus = status
        when (allergyHistoryStatus) {
            1 -> {
                mBinding.edtAllergicHistory.visible()
                setDrawableLeft(mBinding.btnHaveAllergicHistory, true)
                setDrawableLeft(mBinding.btnNotHaveAllergicHistory, false)
            }

            0 -> {
                mBinding.edtAllergicHistory.gone()
                setDrawableLeft(mBinding.btnHaveAllergicHistory, false)
                setDrawableLeft(mBinding.btnNotHaveAllergicHistory, true)
            }
        }

    }


    private fun isNeedListener(isNeed: Boolean) {
        if (isNeed) {
            mBinding.apply {
                btnHavePastHistory.onClick {
                    setPastHistory(1)
                }
                btnNotHavePastHistory.onClick {
                    setPastHistory(0)
                }

                btnHavePHI.onClick {
                    setPresentDisease(1)
                }
                btnNotHavePHI.onClick {
                    setPresentDisease(0)
                }

                btnHaveAllergicHistory.onClick {
                    setAllergyHistory(1)
                }
                btnNotHaveAllergicHistory.onClick {
                    setAllergyHistory(0)
                }

                tvDiagnosis.onClick {
                    val intent = Intent(this@AddInquiryCaseHistory, DiagnoseActivity::class.java)
                    intent.putExtra(KEY_CONSULT_TYPE, "1")
                    mActivityResultLauncher.launch(intent)
                }

//                edtHeight.textChangeFlow()
//                    .distinctUntilChanged()
//                    .debounce(500)
//                    .flowOn(Dispatchers.IO)
//                    .onEach {
//                        //这里走查询接口
//                        height = edtHeight.text.toString().trim() //身高
//                        setBmi()
//                    }
//                    .launchIn(lifecycleScope)


//                edtWeight.textChangeFlow()
//                    .distinctUntilChanged()
//                    .debounce(500)
//                    .flowOn(Dispatchers.IO)
//                    .onEach {
//                        //这里走查询接口
//                        weight = edtWeight.text.toString().trim() //身高
//                        setBmi()
//                    }
//                    .launchIn(lifecycleScope)

                tvAccept.onClick {
                    setCaseData()
                }
            }
        }

    }


    private fun setBmi() {
//        if (!height.isNullOrEmpty() && !weight.isNullOrEmpty()) {
//            val heightMeter = BigDecimalUtils.div(height, "100", 2)
//            bmi = BigDecimalUtils.div(
//                weight,
//                BigDecimalUtils.mul(heightMeter.toDouble(), heightMeter.toDouble(), 2),
//                2
//            )//体重(公斤)除以身高(米)的平方
//            mBinding.edtBmi.text = bmi
//        }

    }

    private fun setDrawableLeft(textView: TextView, isHave: Boolean) {
        val drawable =
            if (isHave) getDrawableResource(R.mipmap.ic_agreement_select) else getDrawableResource(R.mipmap.ic_agreement_default)
        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight);
        textView.setCompoundDrawables(drawable, null, null, null)
    }


    private fun setCaseData() {

        diseaseDescription = mBinding.edtMainSuit.text.toString().trim()
        if (diseaseDescription.isNullOrEmpty()) {
            showToast("请输入您对患者的病情主诉")
            return
        }

        if (pastHistoryStatus == 1) {
            pastHistoryContent = mBinding.edtPastHistory.text.toString().trim()
            if (pastHistoryContent.isNullOrEmpty()) {
                showToast("请输入既往史")
                return
            }
        }

        if (presentDiseaseStatus == 1) {
            presentDiseaseContent = mBinding.edtPHI.text.toString().trim()
            if (presentDiseaseContent.isNullOrEmpty()) {
                showToast("请输入现病史")
                return
            }
        }

        if (allergyHistoryStatus == 1) {
            allergyHistoryContent = mBinding.edtAllergicHistory.text.toString().trim()
            if (allergyHistoryContent.isNullOrEmpty()) {
                showToast("请输入过敏史")
                return
            }
        }
        if (diagnosisId.isNullOrEmpty()) {
            showToast("请选择诊断")
            return
        }

//        height = mBinding.edtHeight.text.toString().trim() //身高
//        weight = mBinding.edtWeight.text.toString().trim() //体重
//        temperature = mBinding.edtTemperature.text.toString().trim()//体温
//        sphygmus = mBinding.edtPulse.text.toString().trim()//脉搏
//        breathing = mBinding.edtBreathing.text.toString().trim()//呼吸次数
//        heartRate = mBinding.edtHeartRate.text.toString().trim() //心率
//        dbp = mBinding.edtDbp.text.toString().trim()//舒张压
//        sbp = mBinding.edtSbp.text.toString().trim()//收缩压

        height = "" //身高
        weight = "" //体重
        temperature = ""//体温
        sphygmus = ""//脉搏
        breathing = ""//呼吸次数
        heartRate = "" //心率
        dbp = ""//舒张压
        sbp = ""//收缩压
        bmi= ""
        physiqueInspect = mBinding.edtPhysicalExam.text.toString().trim() //体格检查
        entrust = mBinding.edtEntrust.text.toString().trim() //嘱托
        showLoading()
        inquiryCase = CreationInquiryCase(
            patientId,
            consultationId,
            diseaseDescription,
            pastHistoryStatus,
            pastHistoryContent,
            presentDiseaseStatus,
            presentDiseaseContent,
            allergyHistoryStatus,
            allergyHistoryContent,
            diagnosisId,
            height,
            weight,
            bmi,
            temperature,
            sphygmus,
            breathing,
            sbp,
            dbp,
            heartRate,
            physiqueInspect,
            entrust
        )
        when(comeType){
            2->{
                //待办结束
                patientViewModel.addInquiryCaseForPhone(inquiryCase)
            }
            else->{
                patientViewModel.addInquiryCase(inquiryCase)
            }




        }



    }


}